package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ComputerActivity extends AppCompatActivity {

    String text = "";  // 表达式

    Calculator calculator = new Calculator();  // 定义一个计算对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_computer);
        // 找到Button组件
        Button button = findViewById(R.id.btn1);
        // 按钮1 添加事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 更新text，把text显示到TextView上面
                text += "1";
                TextView textView = findViewById(R.id.text_view);
                textView.setText(text);
            }
        });

        Button button2 = findViewById(R.id.btn2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                text += "2";
                TextView textView = findViewById(R.id.text_view);
                textView.setText(text);
            }
        });

        // 加号按钮
        Button buttonAdd = findViewById(R.id.btn_add);
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                text += "+";
                TextView textView = findViewById(R.id.text_view);
                textView.setText(text);
            }
        });

        // 等于按钮
        Button buttonEq = findViewById(R.id.btn_eq);
        buttonEq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String result = calculator.Eval(text).toString();
                TextView textView = findViewById(R.id.text_view);
                textView.setText(result);
            }
        });
    }
}